package com.ygnn.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ygnn.common.Dto.ApiOrderDto;
import com.ygnn.common.R.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:ApiController
 * Package:com.ygnn.controller
 * Description:
 *
 * @Author: dlh
 * @Creat:2024/10/13-20:21
 */
@RestController
@RequestMapping("/api")
@CrossOrigin
@Api(value = "Api接口", tags = {"Api接口"})
public class ApiController {
    @ApiOperation("新增订单")
    @PostMapping("/selectByUid")
    public Result selectByUid(@RequestParam String uid) {
        String url = "http://wk2021.asia/jingyu/lp/api.php?act=get_user_info";
        String cookie = "admin_token=78faWQZ%2B1tt%2BF40LcWvUWMmWR4L0kCVlM7l11qk670qX2vQXGNucGZrhoZH65Sgtd3M%2BfjVllG11So%2F22RwSGL1aA39nEwVD; td_cookie=2948505334; PHPSESSID=t5mkh3rbj2kl7d28t1k5savo8e";
        try {
            // 创建URL对象
            URL obj = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            // 设置请求头
            connection.setRequestProperty("Cookie", cookie);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 构造请求体
            String urlParameters = "uid=" + uid;

            // 发送POST请求
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            // 获取响应代码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code : " + responseCode);
            final Object content = connection.getContent();
            System.err.println(content.toString());

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 输出响应内容
            String jsonResponse = response.toString();
            JSONObject jsonObject = JSON.parseObject(jsonResponse);
            int code = jsonObject.getIntValue("code");
            if (code == 0) {
                return Result.success("该账号已授权");
            } else {
                return Result.error("请先授权");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("未知错误");
        }
    }

    @ApiOperation("新增订单")
    @PostMapping("/add")
    public Result add(@RequestBody ApiOrderDto apiOrderDto) {
        // 定义期望的时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建 POST 请求
            HttpPost post = new HttpPost("http://wk2021.asia/jingyu/lp/api.php?act=add");

            // 添加请求头
            post.setHeader("Content-Type", "application/x-www-form-urlencoded");
            post.setHeader("Cookie", "admin_token=78faWQZ%2B1tt%2BF40LcWvUWMmWR4L0kCVlM7l11qk670qX2vQXGNucGZrhoZH65Sgtd3M%2BfjVllG11So%2F22RwSGL1aA39nEwVD; td_cookie=2948505334; PHPSESSID=stn4ndfep2fln12bcmdrq4is5c");
            post.setHeader("Origin", "http://wk2021.asia");
            post.setHeader("Referer", "http://wk2021.asia/index/jylep");

            // 构建请求体
            String urlParameters = "form[student_id]="+apiOrderDto.getStudent_id()
                    + "&form[uid]="+apiOrderDto.getUid()
                    + "&form[run_type]="+apiOrderDto.getAuth_type()
                    + "&form[dis]="+apiOrderDto.getDis()
                    + "&form[zone_id]="+apiOrderDto.getZone_id()
                    + "&form[is_jrxy]="+apiOrderDto.getIs_jrxy()
                    + "&form[task_list][0][start_time]="+apiOrderDto.getStart_time()
                    + "&form[zone_name]=晋中学院"
                    + "&form[school_name]=晋中学院"
                    + "&form[is_auth]=1"
                    + "&form[auth_type]=微信"
                    + "&form[auth_time]="+ LocalDateTime.now().format(formatter);

            // 设置请求体
            post.setEntity(new StringEntity(urlParameters));

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                // 读取响应内容
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
                System.out.println("Response: " + responseBody);
                JSONObject jsonObject = JSON.parseObject(responseBody);
                int code = jsonObject.getIntValue("code");
                if (code==1){
                    return Result.success("新增成功");
                }else{
                    return Result.error("新增失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("未知异常");
        }
    }
}


